/**
 * http://usejsdoc.org/
 * @web static
 */
var http = require('http'),
	fs = require('fs'),
	url = require('url');


function goIndex(res){
	var realPath = __dirname + '/'+ url.parse('index.html').pathname;
	var indexPage = fs.readFileSync(realPath);
	res.writeHead( 200 , {"Content-Type":"text/html"});
	res.end(indexPage);
}

/**
 * 解析静态文件数据
 * @param pathname 路径名称
 * @param realPath 真实路径
 * @param res http响应对象
 */
function dealWithStatic(pathname,realPath,res){
	fs.exists(realPath,function(exists){
		if(!exists){
			res.writeHead( 404 , {"Content-Type":"text/plain"});
			res.write('This request URL '+pathname+' was not found on this server.');
			res.end();
		}else{
			var pointPostion = pathname.lastIndexOf('.'),
				mmieString = pathname.substring(pointPostion+1),//获取文件后缀名
				mmieType;
			
			switch (mmieString) {
			case 'css': mmieType = 'text/css';
				break;
			case 'png': mmieType = 'image/jpg';
			break;
			default: mmieType = 'text/plain';
				break;
			}
			
			fs.readFile(realPath, "binary",function(err,file){
				if(err){
					res.writeHead( 500 , {'Content-Type':'text/plain'});
					res.end(err);
				}else{
					res.writeHead( 200 , {'Content-Type':mmieType});
					res.write(file,"binary");
					res.end();
				}
				
			});
		}
	});
}

/**创建http服务器*/
http.createServer(function(req,res){
	/**web客户端请求*/
	var pathname = url.parse(req.url).pathname;//获取url请求路径
	var realPath = __dirname +'/static'+ pathname;
	if('/favicon.ico' === pathname){
		return;
	}else if(pathname === '/index' || pathname === '/'){
		goIndex(res);
	}else{
		dealWithStatic(pathname,realPath,res);
	}
}).listen(8080,'127.0.0.1');

console.log('Server running at http://127.0.0.1:8080');